/*
 * Copyright 2019 xiaomaoguai.com All right reserved. This software is the
 * confidential and proprietary information of xiaomaoguai.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with xiaomaoguai.com.
 */

package com.xiaomaoguai.core.next.apm.jaeger;

import org.slf4j.MDC;

import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.util.ThreadLocalScopeManager;

/**
 * 将jaeger调用链的traceID等信息，存放到日志 MDC 上下文中，打印日志的时候输出traceId信息。
 *
 * @author chenyao
 * @since 2019年11月13日 下午5:13:56
 */
public class WrappedThreadLocalScopeManager extends ThreadLocalScopeManager {
    public void putB3TraceInfo(Span span) {
        if (span != null && span.context() != null) {
            String[] traceInfo = span.context().toString().split(":");
            if (traceInfo.length == 4) {
                MDC.put("X-B3-TraceId", traceInfo[0]);
                MDC.put("X-B3-SpanId", traceInfo[1]);
                MDC.put("X-B3-ParentSpanId", traceInfo[2]);
            }
        }
    }

    @Override
    public Scope activate(Span span, boolean finishOnClose) {
        putB3TraceInfo(span);
        return super.activate(span, finishOnClose);
    }

    @Override
    public Scope activate(Span span) {
        putB3TraceInfo(span);
        return super.activate(span);
    }
}
